from flask import Blueprint, request, session, current_app
from models.basicInfo import BasciInfoModel
from models.img import ImageModel
from utils import restful
from hooks import login_auth
from exts import db


bp = Blueprint('baike', __name__, url_prefix='/baike')


# 1、根据名称获取少数民族百科
@bp.route('/get/<string:name>', methods=['GET'])
def get_minority_info_by_name(name):
    res = '暂无该民族百科信息，正在加急整理编写中...'
    bk = BasciInfoModel.query.filter_by(name=name).one_or_none()
    if bk:
        res = bk.info
    return restful.ok(data={'content': res})


# 2、根据id获取baike信息
@bp.route('/get/<int:bid>', methods=['GET'])
def get_minority_info_by_id(bid):
    bk = BasciInfoModel.query.get(bid)
    if bk:
        return restful.ok(data={"baike": bk.to_dict()})
    return restful.params_error()


# 3、获取所有的百科信息
@bp.route('/getAll', methods=['GET'])
def get_minority_all():
    bks = BasciInfoModel.query.all()
    res = []
    for b in bks:
        tmp = b.to_dict(choice='simple')
        res.append(tmp)
    return restful.ok(data={'baikes': res})


# 4、上传新的百科
@bp.route('/create', methods=['POST'])
@login_auth
def create_minority_info():
    # 1、获取前端json数据
    data = request.json
    # 2、更新数据库 basicinfomodel ImageModel
    bk = BasciInfoModel(name=data.get('name'), info=data.get('info'))
    db.session.add(bk)
    db.session.flush()
    images = []
    if data.get('imgs'):
        for u in data.get('imgs'):
            if u:
                image = ImageModel(article_id=bk.info_id, type='baike', url=u)
                images.append(image)
    db.session.add_all(images)
    db.session.commit()
    return restful.ok(message='上传成功', data=str(bk.info_id))


# 5、修改百科信息
@bp.route('/update/<int:info_id>', methods=['POST'])
@login_auth
def update_minority_info(info_id):
    data = request.json
    bk = BasciInfoModel.query.get(info_id)
    return restful.ok()


# 6、删除百科信息
@bp.route('/delete/<int:info_id>', methods=['DELETE'])
@login_auth
def delete_minority_info(info_id):
    bk = BasciInfoModel.query.get(info_id)
    if bk:
        db.session.delete(bk)
        db.session.commit()
    else:
        return restful.params_error()
    return restful.ok(message='删除成功')
